package gui;

import classes.Servidor;
import controlador.LoginControlador;
import erro.ConexaoException;
import erro.ConsultaException;
import fachada.Fachada;
import java.awt.event.KeyEvent;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import rn.FormataString;

/**
 *
 * @author Roberta
 */
public class ServidorExibir extends javax.swing.JFrame {

    public static String matricula;

    /** Creates new form ServidorExibir */
    public ServidorExibir() {
        initComponents();
        this.setIconImage(Login.icone.getImage());
        this.setLocationRelativeTo(null);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btAlterar = new javax.swing.JButton();
        lbNivel = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbDadosServidor = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Dados do Servidor");

        btAlterar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/editar.png"))); // NOI18N
        btAlterar.setText("Alterar");
        btAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAlterarActionPerformed(evt);
            }
        });
        btAlterar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                btAlterarKeyPressed(evt);
            }
        });

        lbNivel.setForeground(new java.awt.Color(0, 102, 153));

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        tbDadosServidor.setFont(new java.awt.Font("Tahoma", 1, 11));
        tbDadosServidor.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"Matricula:", null},
                {"CPF:", null},
                {"Nome:", null},
                {"Data de nascimento:", null},
                {"E-mail Profissional:", null},
                {"E-mail Pessoal:", null},
                {"Telefone do Setor:", null},
                {"Telefone:", null},
                {"Telefone 2:", null},
                {"Telefone Funcional:", null},
                {"Lotação:", null},
                {"Cargo Efetivo:", null},
                {"Cargo Comissão:", null},
                {"Rua:", null},
                {"Bairro:", null},
                {"Cidade:", null},
                {"UF:", null},
                {"CEP:", null}
            },
            new String [] {
                "Dados", "Servidor"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tbDadosServidor);
        tbDadosServidor.getColumnModel().getColumn(0).setMinWidth(135);
        tbDadosServidor.getColumnModel().getColumn(0).setPreferredWidth(165);
        tbDadosServidor.getColumnModel().getColumn(0).setMaxWidth(165);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 375, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE)
                .addContainerGap())
        );

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/atualizar.png"))); // NOI18N
        jButton1.setText("Cadastrar Gozo");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbNivel)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btAlterar)
                    .addComponent(jButton1))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btAlterar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 306, Short.MAX_VALUE)
                        .addComponent(jButton1))
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lbNivel))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAlterarActionPerformed
        ServidorEditar se = new ServidorEditar();
        if (LoginControlador.nivel == 2) {
            se.panelAcesso.setVisible(false);
        }
        se.carregarCombos();
        se.carregarText();//Método para carregar os JTextBox com os valores do servidor pesquisado.
        se.setVisible(true);
        this.dispose();
    }//GEN-LAST:event_btAlterarActionPerformed

    private void btAlterarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btAlterarKeyPressed
        if (KeyEvent.getKeyText(evt.getKeyCode()).equals("Enter")) {
            btAlterarActionPerformed(null);
        }
    }//GEN-LAST:event_btAlterarKeyPressed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        GozoCadastrar g = new GozoCadastrar();
        g.setLocationRelativeTo(null);
        g.setVisible(true);
    }//GEN-LAST:event_jButton1ActionPerformed

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ServidorExibir.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ServidorExibir.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ServidorExibir.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ServidorExibir.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new ServidorExibir().setVisible(true);
            }
        });
    }

    public void carregarTabela(){
        
        try {
            DefaultTableModel modelo = (DefaultTableModel) tbDadosServidor.getModel();
            Fachada f = new Fachada();
            Servidor s = new Servidor();
            s.setMatricula(ServidorExibir.matricula);
            String nivel = "Nível de acesso: ";
            Servidor lista = f.pesquisar(s);
            if (lista.getNivelAcesso() != 0) {

                switch (lista.getNivelAcesso()) {
                    case 1:
                        nivel += "Administrador";
                        break;
                    case 2:
                        nivel += "Master";
                        break;
                    case 3:
                        nivel += "Usuário";
                        break;
                    case 4:
                        nivel += "Desabilitado";
                        break;
                }
                lbNivel.setText(nivel);
            }            
            if (lista.getNasc() != null) {
                DateFormat formatdata = new SimpleDateFormat("dd-MM-yyyy");
                Date dataNasc = lista.getNasc();
                String nasc = (formatdata.format(dataNasc));
                modelo.setValueAt(nasc, 3, 1);
            } else {
                modelo.setValueAt(null, 3, 1);
            }  
            try {
                modelo.setValueAt(FormataString.formatarCpf(String.valueOf(lista.getMatricula()), ("#####-#")), 0, 1);
            } catch (ParseException ex) {
                modelo.setValueAt(lista.getMatricula(), 0, 1);
            }            
            try {
                modelo.setValueAt(FormataString.formatarCpf(lista.getCpf(), ("###.###.###-##")), 1, 1);
            } catch (ParseException ex) {
                modelo.setValueAt(lista.getCpf(), 1, 1);
            }
            modelo.setValueAt(lista.getNome(), 2, 1);
            modelo.setValueAt(lista.getEmailProf(), 4, 1);
            modelo.setValueAt(lista.getEmailPessoal(), 5, 1);
            modelo.setValueAt(lista.getTelefoneSetor(), 6, 1);
            modelo.setValueAt(lista.getTelefone1(), 7, 1);
            modelo.setValueAt(lista.getTelefone2(), 8, 1);
            modelo.setValueAt(lista.getTelefoneFunc(), 9, 1);
            modelo.setValueAt(lista.getLotacao().getSigla(), 10, 1);
            modelo.setValueAt(lista.getCargoE().getNome(), 11, 1);
            modelo.setValueAt(lista.getCargoC().getNome(), 12, 1);
            modelo.setValueAt(lista.getRua() + " - " + lista.getNumero(), 13, 1);
            modelo.setValueAt(lista.getBairro(), 14, 1);
            modelo.setValueAt(lista.getCidade(), 15, 1);
            modelo.setValueAt(lista.getEstado(), 16, 1);
            modelo.setValueAt(lista.getCep(), 17, 1);

            tbDadosServidor.setModel(modelo);
        } catch (ConexaoException ex) {
            JOptionPane.showMessageDialog(null, "Não foi possível conectar-se ao banco de dados!\n" + ex);
        } catch (ConsultaException ex) {
            JOptionPane.showMessageDialog(null, "Ocorreu um erro ao tentar carregar a tela.\n" + ex);
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    public javax.swing.JButton btAlterar;
    private javax.swing.JButton jButton1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    public javax.swing.JLabel lbNivel;
    public javax.swing.JTable tbDadosServidor;
    // End of variables declaration//GEN-END:variables
}
